/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.panpf.sketch.sample.ui;

import me.panpf.sketch.sample.AssetImage;
import me.panpf.sketch.sample.ResourceTable;
import me.panpf.sketch.sample.bean.Image;
import me.panpf.sketch.sample.event.Events;
import me.panpf.sketch.sample.util.PxUtil;
import me.panpf.sketch.util.Log;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;

/**
 * BlockDisplayTestFraction
 */
public class BlockDisplayTestFraction extends Fraction {

    private PageSlider pagerPagerTabFractionContent;
    private DirectionalLayout tabPagerTabFractionTabs;

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        Component component = LayoutScatter.getInstance(getFractionAbility()).parse(ResourceTable.Layout_fraction_block_display_test, null, false);

        tabPagerTabFractionTabs = (DirectionalLayout) component.findComponentById(ResourceTable.Id_tab_pagerTabFraction_tabs);
        pagerPagerTabFractionContent = (PageSlider) component.findComponentById(ResourceTable.Id_pager_pagerTabFraction_content);
        initViewSlider();
        return component;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        initRadio();
    }

    @Override
    protected void onActive() {
        super.onActive();

    }

    private void initViewSlider() {
        List<PageViewDate> pageViewDates = new ArrayList<>();
        for (int i = 0; i < AssetImage.HUGE_IMAGES.size(); i++) {
            pageViewDates.add(new PageViewDate(AssetImage.HUGE_IMAGES.get(i)));
        }

        pagerPagerTabFractionContent.setProvider(new ImagePageProvider(getFractionAbility(), pageViewDates));
        pagerPagerTabFractionContent.setPageCacheSize(4);
        pagerPagerTabFractionContent.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i0, float v1, int i1) {
            }

            @Override
            public void onPageSlideStateChanged(int i1) {
            }

            @Override
            public void onPageChosen(int i1) {
                initShowPageView(i1);
                setRadioCheck(i1);
            }
        });
    }

    private void initShowPageView(int i1) {
        try {
            List<PageViewDate> dateList = ((ImagePageProvider) pagerPagerTabFractionContent.getProvider()).getDateList();
            if (dateList.get(i1) == null) {
                return;
            }

            for (int j = 0; j < dateList.size(); j++) {
                if (dateList.get(j).fragment != null) {
                    dateList.get(j).fragment.setUserVisibleHint(false);
                }
            }
            if (dateList.get(i1).stackLayout != null && dateList.get(i1).fragment == null) {
                ImageFraction imageFragment = new ImageFraction.ImageFragmentBuild(new Image(dateList.get(i1).url, dateList.get(i1).url), null, true, handler).build(getFractionAbility());
                dateList.get(i1).fragment = imageFragment;
                getFractionAbility().getFractionManager().startFractionScheduler().replace(dateList.get(i1).stackLayout.getId(), imageFragment).submit();
            }
            dateList.get(i1).fragment.setUserVisibleHint(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void setRadioCheck(int check) {
        List<RadioButton> list = new ArrayList<>();
        for (int i = 0; i < tabPagerTabFractionTabs.getChildCount(); i++) {
            if (tabPagerTabFractionTabs.getComponentAt(i) instanceof RadioButton) {
                list.add((RadioButton) tabPagerTabFractionTabs.getComponentAt(i));
            }
        }
        if (check < list.size()) {
            list.get(check).setChecked(true);
        }
    }

    private void initRadio() {
        tabPagerTabFractionTabs.removeAllComponents();
        String[] items = new String[]{"WORLD", "QMSHT", "CWB", "CARD"};
        for (int i = 0; i < items.length; i++) {
            RadioButton radioButton = new RadioButton(getFractionAbility());
            radioButton.setText(items[i]);
            radioButton.setTextColor(Color.WHITE);
            radioButton.setTextColorOn(Color.WHITE);
            radioButton.setTextColorOff(Color.GRAY);
            radioButton.setButtonElement(new ShapeElement());
            radioButton.setPadding(20, 20, 20, 20);
            radioButton.setTextSize(AttrHelper.fp2px(12, getFractionAbility()));
            radioButton.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    setTabChecked(component);
                }
            });
            tabPagerTabFractionTabs.addComponent(radioButton);
        }
        ((RadioButton) tabPagerTabFractionTabs.getComponentAt(0)).setChecked(true);

        getFractionAbility().getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                initShowPageView(0);
            }
        }, 10);

    }

    private void setTabChecked(Component checked) {
        for (int i = 0; i < tabPagerTabFractionTabs.getChildCount(); i++) {
            RadioButton radioButton = (RadioButton) tabPagerTabFractionTabs.getComponentAt(i);
            if (checked == radioButton) {
                pagerPagerTabFractionContent.setCurrentPage(i);
            }
        }
    }

    /**
     * ImagePageProvider
     */
    public static final class ImagePageProvider extends PageSliderProvider {
        List<PageViewDate> dateList = new ArrayList();
        Context context;

        public ImagePageProvider(Context context, List<PageViewDate> dateList) {
            this.dateList = dateList;
            this.context = context;
        }

        /**
         * getDateList
         *
         * @return List<PageViewDate>
         */
        public List<PageViewDate> getDateList() {
            return dateList;
        }

        @Override
        public int getCount() {
            return dateList.size();
        }

        @Override
        public Object createPageInContainer(ComponentContainer componentContainer, int i1) {
            PageViewDate pageViewDate = dateList.get(i1);
            if (pageViewDate.stackLayout == null || pageViewDate.stackLayout.getComponentParent() != null) {
                pageViewDate.stackLayout = (StackLayout) LayoutScatter.getInstance(context).parse(ResourceTable.Layout_stacklayout, null, false);
                pageViewDate.stackLayout.setId(PxUtil.generateViewId());
            }
            componentContainer.addComponent(pageViewDate.stackLayout);
            return pageViewDate.stackLayout;
        }


        @Override
        public void destroyPageFromContainer(ComponentContainer componentContainer, int i1, Object o1) {
            componentContainer.removeComponent((Component) o1);
        }

        @Override
        public boolean isPageMatchToObject(Component component, Object o1) {
            return component == o1;
        }
    }

    /**
     * PageViewDate
     */
    public static class PageViewDate {
        String url;
        StackLayout stackLayout;
        ImageFraction fragment;

        /**
         * PageViewDate
         *
         * @param url
         */
        public PageViewDate(String url) {
            this.url = url;
        }
    }

    EventHandler handler = new EventHandler(EventRunner.getMainEventRunner()) {
        @Override
        protected void processEvent(InnerEvent event) {
        }
    };


}
